package com.example.springbootvuetest.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootvuetest.Utils.TokenUtils;
import com.example.springbootvuetest.base.Result;
import com.example.springbootvuetest.base.ResultCode;
import com.example.springbootvuetest.entity.User;
import com.example.springbootvuetest.entity.dto.UserDto;
import com.example.springbootvuetest.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    @GetMapping("/login")
    public Result<UserDto> login(
            @RequestParam(name = "accountNumber") String accountNumber,
            @RequestParam(name = "userPassword") String userPassword
    ){
        if (StrUtil.isBlank(accountNumber) || StrUtil.isBlank(userPassword))
            return Result.error("参数错误");
        return userService.login(accountNumber, userPassword);
    }
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        return userService.register(user);
    }

    @GetMapping("/info")
    public Result<UserDto> getUserInfo(@RequestParam("id") Integer id) {
        User one = userService.getById(id);
        UserDto userDto = new UserDto();
        BeanUtil.copyProperties(one, userDto, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return Result.success(userDto);
    }

    /**
     * 修改密码
     *
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @GetMapping("/password")
    public Result updateUserPassword(@RequestParam("id") String id,
                                     @RequestParam("oldPassword") String oldPassword,
                                     @RequestParam("newPassword") String newPassword) {
        if (userService.updatePassword(newPassword, oldPassword, id)) {
            return Result.success();
        }
        return Result.error(ResultCode.PASSWORD_ERROR);
    }

}
